package be.msec.client.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class ByteUtils {

	public static short getShort(byte[] data, int offset) {
		return (short) (((data[offset] << 8)) | ((data[offset + 1] & 0xff)));
	}

	public static byte[] shortToByteArray(short s) {
		return new byte[] { (byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF) };
	}
	
	public static int getInteger(byte[] data, int offset) {
		return (((data[offset] << 24)) | ((data[offset + 1] & 0xff) << 16) | ((data[offset + 2] & 0xff) << 8) | ((data[offset + 3] & 0xff)));
	}

	public static byte[] integerToByteArray(int s) {
		return new byte[] { (byte) ((s & 0xFF000000) >> 24), (byte) ((s & 0x00FF0000) >> 16),(byte) ((s & 0x0000FF00) >> 8),(byte) (s & 0x000000FF) };
	}

	public static byte[] longToByteArray(long s) {
		try{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			DataOutputStream dos = new DataOutputStream(bos);  
			dos.writeLong(s);  
			dos.flush();  
			return bos.toByteArray();
		}catch(IOException ioe){
			return null;
		}
	}
	
	public static long getLong(byte[] data, int offset){
		try{
			byte[] temp = ArrayUtils.getSubArray(data, offset, 8);
			ByteArrayInputStream bis = new ByteArrayInputStream(temp);
			DataInputStream dis = new DataInputStream(bis);
			return dis.readLong();
		}catch(IOException ioe){
			return 0L;
		}
	}
}
